/*
 * comlan
 */

package com.promfy.net.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.content.Context;
import android.util.Log;

public class NetWork {

	private static final String TAG = "network";
	private static String sender;
	private static String callback;
	private Context context;


	public NetWork(Context context) {
		super();
		this.context = context;

	}

	/**************************** base method *******************************/
	/**
	 * @param callbackListener2 
	 * 
	 */
	public static String doGet(String url, String json) throws Exception {
		String result = null;
		//url = url + "?" + name1=value1&name2=value2
		url = url + "?";
		JSONArray jsonArray = new JSONArray(json);
		for(int i = 0; i < jsonArray.length(); i++){
			JSONArray ja = (JSONArray) jsonArray.get(i);
			String key = ja.getString(0);
			String value = ja.getString(1);
			url += key + "=" + value + "&";
		}
		url = url.substring(0, url.length()-1);
		Log.d(TAG, "[NetWork] doGet() url = " + url);
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			result = EntityUtils.toString(httpResponse.getEntity());
		}
		String jsCallback =  callback + "('" + sender + "'," + "'true'," + "''," + "'" + result + "')";

		Log.d(TAG, "[NetWork] doGet() jsCallback = " + jsCallback);

		return result;
	}
	
	public static String doPost(String url, String json) throws Exception{
		String result = null;
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONArray jsonArray = new JSONArray(json);
		for(int i = 0; i < jsonArray.length(); i++){
			JSONArray ja = (JSONArray) jsonArray.get(i);
			String key = ja.getString(0);
			String value = ja.getString(1);
			params.add(new BasicNameValuePair(key, value));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			result = EntityUtils.toString(httpResponse.getEntity());
		}
		String jsCallback =  callback + "('" + sender + "'," + "'true'," + "'success'," + "'" + result + "')";

		Log.d(TAG, "[NetWork] doPost() jsCallback = " + jsCallback);

		return result;
	}

}
